package com.eastfair.auth.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.eastfair.auth.dao.OrganizationRoleMapper;
import com.eastfair.auth.entity.Organization;
import com.eastfair.auth.entity.OrganizationRole;
import com.eastfair.auth.service.OrganizationRoleService;
import com.eastfair.boot.service.SuperCacheServiceImpl;
import com.eastfair.businpoint.BusinLoadUserPermissOfOrgPoint;
import com.eastfair.cache.auth.OrgRoleCacheKeyBuilder;
import com.eastfair.cache.repository.CacheOps;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.model.CacheKeyBuilder;
import com.eastfair.log.point.PointUtil;
import com.eastfair.projectcore.api.ProjectCoreServiceFeign;
import com.eastfair.core.snowflake.DefaultUidGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 *
 * </p>
 *
 * @author ligang
 * @date 2021-08-30
 */
@Slf4j
@Service
@DS("#thread.tenant")
public class OrganizationRoleServiceImpl extends SuperCacheServiceImpl<OrganizationRoleMapper, OrganizationRole> implements OrganizationRoleService {
    @Autowired
    ProjectCoreServiceFeign projectCoreServiceFeign;

    @Autowired
    protected CacheOps cacheOps;

    @Autowired
    private PointUtil pointUtil;

    @Override
    protected CacheKeyBuilder cacheKeyBuilder() {
        return new OrgRoleCacheKeyBuilder();
    }

    /**************sharding 分库分表操作 *****************/
    @Override
    public boolean updateByIdOfShard(OrganizationRole entity) {
        UpdateWrapper<OrganizationRole> updateWrapper = new UpdateWrapper<>();
        //可将指定字段更新为null
        updateWrapper.lambda().eq(OrganizationRole::getProjectId, entity.getProjectId()).eq(OrganizationRole::getId, entity.getId());
        entity.setProjectId(null);
        //删除缓存
        delCache(entity);
        return SqlHelper.retBool(this.getBaseMapper().update(entity, updateWrapper));
    }


    /**
     * 处理新增相关处理
     *
     * @param model 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerSave(OrganizationRole model) {
        //雪花ID
        model.setId(DefaultUidGenerator.getUidOfProjectId(model.getProjectId()));
        return R.successDef();
    }


    @Override
    public R addOrgRole(List<Organization> organizationList, List<Long> roleIds, Long projectId) {
        if (roleIds != null && !roleIds.isEmpty()) {
            for (Organization organization : organizationList) {
                for (Long roleId : roleIds) {
                    OrganizationRole orgRole1 = new OrganizationRole();
                    orgRole1.setOrganizationId(organization.getId());
                    orgRole1.setRoleId(roleId);
                    orgRole1.setProjectId(projectId);
                    save(orgRole1);
                }
            }

            //添加到事件监听队列
            BusinLoadUserPermissOfOrgPoint businLoadUserPermissOfOrgPoint = new BusinLoadUserPermissOfOrgPoint();
            businLoadUserPermissOfOrgPoint.setOrgIdList(organizationList.stream().map(Organization::getId).collect(Collectors.toList()));
            businLoadUserPermissOfOrgPoint.setProjectId(ContextUtil.getProjectId());
            pointUtil.addBusinPointMsg(businLoadUserPermissOfOrgPoint);
        }
        return R.success();
    }


    @Override
    public R removeOrgRole(List<Organization> organizationList, List<Long> roleIds, Long projectId) {
        if (roleIds != null && !roleIds.isEmpty()) {
            List<Long> orgIds = organizationList.stream().map(Organization::getId).collect(Collectors.toList());
            OrganizationRole organizationRole = new OrganizationRole();
            organizationRole.setProjectId(projectId);
            List<OrganizationRole> orgRoleList = list(organizationRole, orgIds, roleIds);
            if (orgRoleList != null && !orgRoleList.isEmpty()) {
                for (OrganizationRole orgRole1 : orgRoleList) {
                    orgRole1.setIsDeleted(BusinessConstant.DELETE_YES);
                    orgRole1.setProjectId(projectId);
                    updateByIdOfShard(orgRole1);
                }

                //添加到事件监听队列
                BusinLoadUserPermissOfOrgPoint businLoadUserPermissOfOrgPoint = new BusinLoadUserPermissOfOrgPoint();
                businLoadUserPermissOfOrgPoint.setOrgIdList(orgIds);
                businLoadUserPermissOfOrgPoint.setProjectId(ContextUtil.getProjectId());
                pointUtil.addBusinPointMsg(businLoadUserPermissOfOrgPoint);
            }
        }
        return R.success();
    }

    @Override
    public R removeOfRole(List<Long> roleIds) {
        List<OrganizationRole> orgRoleList = list(null, null, roleIds);
        if (orgRoleList != null && !orgRoleList.isEmpty()) {
            for (OrganizationRole orgRole1 : orgRoleList) {
                orgRole1.setIsDeleted(BusinessConstant.DELETE_YES);
                updateByIdOfShard(orgRole1);
            }

            //添加到事件监听队列
            BusinLoadUserPermissOfOrgPoint businLoadUserPermissOfOrgPoint = new BusinLoadUserPermissOfOrgPoint();
            businLoadUserPermissOfOrgPoint.setOrgIdList(orgRoleList.stream().map(OrganizationRole::getOrganizationId).collect(Collectors.toList()));
            businLoadUserPermissOfOrgPoint.setProjectId(ContextUtil.getProjectId());
            pointUtil.addBusinPointMsg(businLoadUserPermissOfOrgPoint);
        }
        return R.success();
    }

    @Override
    public List<OrganizationRole> findOfRole(List<Long> roleIds) {
        return list(null, null, roleIds);
    }

    @Override
    public List<OrganizationRole> findOfOrg(List<Long> orgIds) {
        return list(null, orgIds, null);
    }

    @Override
    public List<OrganizationRole> list(OrganizationRole orgRole, List<Long> orgIds, List<Long> roleIds) {
        //查询
        QueryWrapper<OrganizationRole> queryWrapper = new QueryWrapper<>();
        if (orgRole != null) {
            if (orgRole.getId() != null) {
                queryWrapper.lambda().eq(OrganizationRole::getId, orgRole.getId());
            }
            if (orgRole.getRoleId() != null) {
                queryWrapper.lambda().eq(OrganizationRole::getRoleId, orgRole.getRoleId());
            }

            if (orgRole.getOrganizationId() != null) {
                queryWrapper.lambda().eq(OrganizationRole::getOrganizationId, orgRole.getOrganizationId());
            }
        }
        if (orgRole != null && orgRole.getProjectId() != null) {
            queryWrapper.lambda().eq(OrganizationRole::getProjectId, orgRole.getProjectId());
        } else if (ContextUtil.getProjectId() != null) {
            queryWrapper.lambda().eq(OrganizationRole::getProjectId, ContextUtil.getProjectId());
        }

        if (orgIds != null && !orgIds.isEmpty()) {
            queryWrapper.lambda().in(OrganizationRole::getOrganizationId, orgIds);
        }
        if (roleIds != null && !roleIds.isEmpty()) {
            queryWrapper.lambda().in(OrganizationRole::getRoleId, roleIds);
        }
        queryWrapper.lambda().eq(OrganizationRole::getIsDeleted, BusinessConstant.DELETE_NO);
        return list(queryWrapper);
    }

}
